package dao.impl;

import dao.UserDao;
import mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import pojo.FastUser;
import pojo.User;

import java.util.List;

/**
 * @Author: fancyears·milos·malvis
 * @Description:
 * @Date: Created in  2019/4/16 10:52
 * @Modified By:
 */
public class UserDaoImpl implements UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public UserDaoImpl() {
    }

    /**
     * 模拟插入一个User对象
     *
     * @param user
     */
    public int insert(FastUser user) {
        System.out.println("模拟插入User,Username=" + user.getUsername());
        return 1;
    }

    public FastUser getUser(Long userId) {
        User user = new User();
        user.setNickname("Rosy");
        user.setId(userId);
        System.out.println("模拟查询User,Username=" + user.getNickname() + "\t ID=" + user.getId());
        return user;
    }

    public void init() {
        System.out.println("这里是UserDao初始化'");
    }

    public void cleanup() {
        // destruction logic
        System.out.println("这里是UserDao  cleanup'");
    }

    @Override
    public int insert(User user) {
        String sql = "insert USER(username,password) values(?,?)";
        System.out.println(sql);
        return jdbcTemplate.update(sql, user.getUsername(), user.getPassword());
    }

    @Override
    public int delete(Long id) {
        String sql = "delete USER t where t.id= ?";
        System.out.println(sql);
        return jdbcTemplate.update(sql, id);
    }

    @Override
    public List<User> listUser() {
        String sql = "select * from USER";
        System.out.println(sql);
        List<User> result = jdbcTemplate.query(sql, new UserMapper());
        return result;
    }

    @Override
    public User selectUser(Long id) {
        String sql = "select * from USER where id = ?";
        System.out.println(sql);
        return jdbcTemplate.queryForObject(sql, new Object[]{id}, new UserMapper());
    }

    @Override
    public int update(User user) {
        String sql = "update USER t set t.username=? where id = ?";
        System.out.println(sql);
        return jdbcTemplate.update(sql, user.getUsername(), user.getId());
    }
}
